//
//  AppDelegate.m
//  SelfDriving
//
//  Created by apple on 15/8/25.
//  Copyright (c) 2015年 apple. All rights reserved.
//

#import "AppDelegate.h"
#import <CoreLocation/CoreLocation.h>
//#import "UMSocialSinaSSOHandler.h"
//#import "UMSocialQQHandler.h"
//#import "UMSocialWechatHandler.h"
#import "WXApi.h"
#import "WXApiManager.h"
#import <UMSocialCore/UMSocialCore.h>
#import "NSStringAdditions.h"
#import "BusinessService+User.h"
#import <AMapFoundationKit/AMapFoundationKit.h>
#import "ZLPhotoPickerGroup.h"
#import "ReleaseFollowVC.h"
#import "ReleaseCircleVC.h"
#import <SystemConfiguration/CaptiveNetwork.h>
#import "IQKeyboardManager.h"
#import <QMUIKit/QMUIKit.h>
#import "QMUIConfigurationTemplate.h"
#import "AddFileViewController.h"
#import <UMSocialCore/UMSociallogMacros.h>
#import <AlipaySDK/AlipaySDK.h>
#import <AVFoundation/AVFoundation.h>
#import "ValidateHelper.h"

#define kMaxSendCount 1 // 同时发送最大数
#define kBaseIfCloseVoice               @"baseIfCloseVoice"

@interface AppDelegate ()<CLLocationManagerDelegate,MAMapViewDelegate,UIAlertViewDelegate,ECNetworkDelegate,TCResultNoneDelegate,ThinkChatDelegate,WXApiDelegate>
@property (assign, nonatomic) UIBackgroundTaskIdentifier bgTask;

@property (strong, nonatomic) dispatch_block_t expirationHandler;
@property (assign, nonatomic) BOOL jobExpired;
@property (assign, nonatomic) BOOL background;
@property (nonatomic,strong) NSMutableArray *groupArrays;

@property (nonatomic,assign)SystemSoundID soundDidRecMsg;
@property (nonatomic,assign)SystemSoundID soundDidSendMsg;
@property (nonatomic,assign)SystemSoundID soundDidRecNotify;
@property (nonatomic,assign)NSTimeInterval timeNotice;

//xhw2018-3-1加
@property (nonatomic, strong)UILabel *msgCountView;
@end

@implementation AppDelegate{
    //    BMKLocationService *locService;
    CLLocationManager * locationManager;
    NSThread *thread;
    NSData *videoData;
    NSMutableArray *videodata;
    NSMutableArray *_imagdata;
    int k;
    MAMapView *_mapView;
    
}
@synthesize _tableBarController;

+ (instancetype)shareDelegate
{
    return (AppDelegate*)[[UIApplication sharedApplication] delegate];
}
+(AppDelegate*)sharedInstance

{
    
    static AppDelegate *devicedelegatehelper;
    
    static dispatch_once_t devicedelegatehelperonce;
    
    dispatch_once(&devicedelegatehelperonce, ^{
        
        devicedelegatehelper = [[AppDelegate alloc] init];
        
    });
    return devicedelegatehelper;
    
}
//根据状态栏的wifi标志来判断网络类型
- (NSString *)getNetWorkStates{
    NSString *state = [[NSString alloc]init];
    AFNetworkReachabilityManager * afManager = [AFNetworkReachabilityManager sharedManager];
    BOOL iswifi = afManager.reachableViaWiFi;
    BOOL isUseble = afManager.reachable;
    BOOL is4G = afManager.reachableViaWWAN;
    AFNetworkReachabilityStatus *netStatus = afManager.networkReachabilityStatus;
    if (iswifi) {
        NSLog(@"是wifi");
       
    }
    else {
        NSLog(@"不是wifi");
    }
    if (is4G) {
        NSLog(@"是4G");
    }
    else {
        NSLog(@"不是4G");
    }
    
    if (isUseble) {
        NSLog(@"有可用网络");
    }
    else {
        NSLog(@"没有可用网络");
    }
    
    
    switch (afManager.networkReachabilityStatus) {
        case AFNetworkReachabilityStatusUnknown:
            NSLog(@"Unknown");
            break;
        case AFNetworkReachabilityStatusNotReachable:
            NSLog(@"NotReachable");
            break;
        case AFNetworkReachabilityStatusReachableViaWiFi:
             state = @"wifi";
            NSLog(@"wifi");
            break;
        case AFNetworkReachabilityStatusReachableViaWWAN:
            NSLog(@"万维网");
            state = @"万维网";
            break;
        default:
            break;
    }

    return state;
}
    


#pragma mark 网络状态通知
//不展示在通知栏的通知211 209 300 、302、304 、1002、1003、1004、1006、1007、1008、1009、1011
-(void)netstate:(NSNotification *)nots{
    NSString * state = nots.object;
    NSMutableDictionary *dic = [UserDefaults readUserDefaultObjectValueForKey:@"user"];
    NSMutableDictionary *ymopenfire = [UserDefaults readUserDefaultObjectValueForKey:@"ymopenfire"];
    NSMutableDictionary *userLocation = [UserDefaults readUserDefaultObjectValueForKey:@"userLocation"];
    if([state intValue]==1){//连接wifi
        //获取wifi名字
        id info = nil;
        NSArray *ifs = (__bridge_transfer id)CNCopySupportedInterfaces();
        for (NSString *ifnam in ifs) {
            info = (__bridge_transfer id)CNCopyCurrentNetworkInfo((__bridge CFStringRef)ifnam);
            NSString *str = info[@"SSID"];
            NSString *str2 = info[@"BSSID"];
            NSString *str3 = [[ NSString alloc] initWithData:info[@"SSIDDATA"] encoding:NSUTF8StringEncoding];
            NSString *name = [UserDefaults readUserDefaultObjectValueForKey:@"wifiName"];
            if (!name){
                [UserDefaults writeUserDefaultObjectValue:str withKey:@"wifiName"];
            }else{
                if (![name isEqualToString:str]) {
                    [UserDefaults writeUserDefaultObjectValue:str withKey:@"wifiName"];
                }
            }
        }
        NSString *name = [UserDefaults readUserDefaultObjectValueForKey:@"wifiName"];
        [userLocation setObject:name forKey:@"wifi_ssid"];
        if(dic||ymopenfire){
            if (userLocation) {
                [userLocation setObject:@"1" forKey:@"type"];
                [[BusinessService shareInstance]updatewifi:userLocation success:^(id result) {
                } failure:^(id result) {
                }];
            }
        }
    }else{//断开wifi
        NSString *name = [UserDefaults readUserDefaultObjectValueForKey:@"wifiName"];
        if (name) {
            [userLocation setObject:name forKey:@"wifi_ssid"];
            if(dic||ymopenfire){
                if (userLocation) {
                    [userLocation setObject:@"0" forKey:@"type"];
                    [[BusinessService shareInstance]updatewifi:userLocation success:^(id result) {
                    } failure:^(id result) {
                    }];
                }
            }
        }
    }
}


#pragma mark --- 提前请求授权
- (void)getAuthorization
{
 
    //此处获取摄像头授权
    switch ([AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo])
    {
        case AVAuthorizationStatusAuthorized:       //已授权，可使用    The client is authorized to access the hardware supporting a media type.
        {
            NSLog(@"授权摄像头使用成功");
            
            break;
        }
        case AVAuthorizationStatusNotDetermined:    //未进行授权选择     Indicates that the user has not yet made a choice regarding whether the client can access the hardware.
        {
            //则再次请求授权
            [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
                if(granted){    //用户授权成功
                    
                    return;
                } else {        //用户拒绝授权
                    
                    return;
                }
            }];
            break;
        }
        default:                                    //用户拒绝授权/未授权
        {
            
            break;
        }
    }
    
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    //xhw2018-1-30加消息收到祥光音效
    [self initializeAudios];
    
    AFNetworkReachabilityManager * afManager = [AFNetworkReachabilityManager sharedManager];
    [afManager startMonitoring];
    
    //xhw2018-1-2加：解决之前一直打印莫名的报错问题
    [[AVAudioSession sharedInstance] setActive:YES withOptions:AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation error:nil];
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionAllowBluetooth error:nil];
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    
    [self getAuthorization];
     [IQKeyboardManager sharedManager].enable = YES;
    
    [QMUIConfigurationTemplate setupConfigurationTemplate];
    
    [QMUIConfigurationManager renderGlobalAppearances];
    
    // 预加载 QQ 表情，避免第一次使用时卡顿
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [QMUIQQEmotionManager emotionsForQQ];
    });
    
    application.statusBarHidden = NO;
    
    [[NSNotificationCenter defaultCenter]
     addObserver:self
     selector:@selector(netstate:)
     name:KNOTIFICATION_onNetworkChanged
     object:nil];
    _sheigt = SCRE_HEIGHT;
    _swhidth = SCRE_WIDTH;
    videodata = [[NSMutableArray alloc]init];
    _imagdata = [[NSMutableArray alloc]init];
    _groupArrays = [[NSMutableArray alloc]init];
    _imagData = [[NSMutableArray alloc]init];
    
    [AMapServices sharedServices].apiKey = @"86a5a8f0669fe6080cd99e7c992f7880";
    [MAMapServices sharedServices].apiKey = @"86a5a8f0669fe6080cd99e7c992f7880";
    
    _mapView = [[MAMapView alloc]init];
    _mapView.showsUserLocation = YES;
    _mapView.delegate = self;
    _mapView.showsUserLocation = YES;
    
//    //第一次安装提示用户信息
//    NSString *tishi = [UserDefaults readUserDefaultObjectValueForKey:@"yimitishi"];
//    if (tishi.length == 0) {
//        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:@"请保持社交礼仪建立完善的个人资料有利于让别人更好的了解您。我的收益体现了您的社交礼仪和个人价值。广告，欺诈，粗鲁的行为都会被统计处罚" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//        [alert show];
//        [UserDefaults writeUserDefaultObjectValue:@"1" withKey:@"yimitishi"];
//    }
    
    
    
    NSFileManager * fMan = [NSFileManager defaultManager];
    NSString * new_path_b = [NSString stringWithFormat:@"%@/Library/Cache",NSHomeDirectory()];
    NSString * new_path = [NSString stringWithFormat:@"%@/Library/Cache/Images",NSHomeDirectory()];
    NSString * new_path_a = [NSString stringWithFormat:@"%@/Library/Cache/Audios",NSHomeDirectory()];
    if ((![fMan fileExistsAtPath:new_path_b]) || (![fMan fileExistsAtPath:new_path])) {
        [fMan createDirectoryAtPath:new_path_b withIntermediateDirectories:YES attributes:nil error:nil];
        [fMan createDirectoryAtPath:new_path withIntermediateDirectories:YES attributes:nil error:nil];
    }
    if (![fMan fileExistsAtPath:new_path_a]) {
        [fMan createDirectoryAtPath:new_path_a withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    
    
#pragma mark - 友盟
    
    [[UMSocialManager defaultManager] openLog:YES];
    
    [[UMSocialManager defaultManager] setUmSocialAppkey:@"57ad74a1e0f55a03260005fd"];
    
    [self configUSharePlatforms];
    
//    [UMSocialData setAppKey:@"57ad74a1e0f55a03260005fd"];
//    [UMSocialData openLog:YES];
    //如果你要支持不同的屏幕方向，需要这样设置，否则在iPhone只支持一个竖屏方向
//    [UMSocialConfig setSupportedInterfaceOrientations:UIInterfaceOrientationMaskAll];
    
    [ECDevice sharedInstance].delegate = [DeviceDelegateHelper sharedInstance];
    
    
//    [UMSocialWechatHandler setWXAppId:@"wxb24865f78860d795" appSecret:@"2ca038058920f4a238a9fed0bdc5b98e" url:@"http://yimisns.com/"];
//    [UMSocialQQHandler setQQWithAppId:@"1105572854" appKey:@"hVskLke6dYt5Wj1O" url:@"http://yimisns.com/"];
    //         [UMSocialQQHandler setQQWithAppId:@"100424468" appKey:@"c7394704798a158208a74ab60104f0ba" url:@"http://www.umeng.com/social"];
//    [UMSocialQQHandler setSupportWebView:YES];
//
//    [UMSocialSinaSSOHandler openNewSinaSSOWithAppKey:@"3819588771"
//                                              secret:@"9b1f363b1aad215fa58986a89c512869"
//                                         RedirectURL:@"https://api.weibo.com/oauth2/default.html"];
//
    
    //    [UMSocialSinaSSOHandler openNewSinaSSOWithAppKey:@"3921700954"
    //                                              secret:@"04b48b094faeb16683c32669824ebdad"
    //                                         RedirectURL:@"http://sns.whalecloud.com/sina2/callback"];
    
    
    //    _mapManager = [[BMKMapManager alloc]init];
    //    // 如果要关注网络及授权验证事件，请设定     generalDelegate参数
    //    BOOL ret = [_mapManager start:@"0BqHEOkj36dNxwy6N8UGCGwr"  generalDelegate:nil];
    //    if (!ret) {
    //        NSLog(@"manager start failed!");
    //    }
    //    locService = [[BMKLocationService alloc]init];
    //    locService.delegate = self;
    //    [locService startUserLocationService];
    
    
    [[ThinkChat instance] setDebugMode:NO];
    [[ThinkChat instance] application:application didFinishLaunchingWithOptions:launchOptions];
    
    
    prepSendList = [[NSMutableArray alloc] init];
    countSend = 0;
    
    [[ThinkChat instance] initWithServerUrl:kBaseSDKAPIDomain
                                IMServerUrl:kBaseSDKAPIDomainXMPP
                               IMServerName:kBaseSDKAPIDomainXMPPServer
                               IMServerPort:kBaseSDKAPIDomainXMPPPort];
    
    
    
    NSMutableDictionary *dic = [UserDefaults readUserDefaultObjectValueForKey:@"user"];
    NSMutableDictionary *ymopenfire = [UserDefaults readUserDefaultObjectValueForKey:@"ymopenfire"];
    if (ymopenfire) {//第三方自动登陆
        [[BusinessService shareInstance]login3:ymopenfire success:^(id result) {
            [AppDelegate shareDelegate].user = result;
            NSString *uid = [NSString stringWithFormat:@"%@",[AppDelegate shareDelegate].user.uid];
            [dic setObject:uid forKey:@"fuid"];
            [dic setObject:uid forKey:@"uid"];
            [self userDidLogin:uid pwd:[AppDelegate shareDelegate].user.openfire];
            
            [self loginECLoginInfo:uid];
            [self initbar];
        } failure:^(id result) {
            UIStoryboard *customerStoryboard = [UIStoryboard storyboardWithName:@"U"
                                                                         bundle:[NSBundle mainBundle]];
            UIViewController *searchResultDetailController = [customerStoryboard instantiateViewControllerWithIdentifier:@"LoginVC"];
            UINavigationController *navg =[[UINavigationController alloc]initWithRootViewController:searchResultDetailController];
            self.window.rootViewController = navg;
            [self.window makeKeyAndVisible];
        }];
    }else{
        if (!dic) {
            UIStoryboard *customerStoryboard = [UIStoryboard storyboardWithName:@"U"
                                                                         bundle:[NSBundle mainBundle]];
            UIViewController *searchResultDetailController = [customerStoryboard instantiateViewControllerWithIdentifier:@"LoginVC"];
            UINavigationController *navg =[[UINavigationController alloc]initWithRootViewController:searchResultDetailController];
            self.window.rootViewController = navg;
            [self.window makeKeyAndVisible];
        }else{
            [SVProgressHUD showWithStatus:@"自动登录中..."];
            [dic setObject:[ValidateHelper getID] forKey:@"deviceid"];
            [[BusinessService shareInstance] login:dic success:^(id result) {
                [AppDelegate shareDelegate].user = result;
                LoginResponseModel *user = result;
                if([user.code intValue] == -1){
                    UIAlertView *customAlertView;
                    if (customAlertView==nil) {
                        customAlertView = [[UIAlertView alloc] initWithTitle:@"请输入验证码" message:user.msg delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
                    }
                    [customAlertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
                    UITextField *nameField = [customAlertView textFieldAtIndex:0];
                    customAlertView.tag = 1024;
                    nameField.tag = 1025;
                    [customAlertView show];
                    return ;
                }
                
                //xhw2018-2-11加:登录的时候也需要传wifi名字
                NSString *networkStr = [self getNetWorkStates];
                if ([networkStr isEqualToString:@"wifi"]) {
                    NSString *wifiStr = [ValidateHelper GetWifiName];
                    NSMutableDictionary *userLocation = [UserDefaults readUserDefaultObjectValueForKey:@"userLocation"];
                    [userLocation setObject:@"1" forKey:@"type"];
                    [userLocation setObject:wifiStr forKey:@"wifi_ssid"];
                    [[BusinessService shareInstance]updatewifi:userLocation success:^(id result) {
                    } failure:^(id result) {
                    }];
                }
                else {
                    NSMutableDictionary *userLocation = [UserDefaults readUserDefaultObjectValueForKey:@"userLocation"];
                    [userLocation setObject:@"0" forKey:@"type"];
                    [[BusinessService shareInstance]updatewifi:userLocation success:^(id result) {
                    } failure:^(id result) {
                    }];
                }
                //xhw2018-2-11加
                
                
                
                
                NSString *uid = [NSString stringWithFormat:@"%@",[AppDelegate shareDelegate].user.uid];
                [dic setObject:uid forKey:@"fuid"];
                
                [self loginECLoginInfo:uid];
                [self initbar];
                [[BusinessService shareInstance]getUserDetail:dic success:^(id result) {
                    [[AppDelegate shareDelegate] userDidLogin:uid pwd:[dic objectForKey:@"password"]];
                    _user = result;
                    [SVProgressHUD dismiss];
                } failure:^(id result) {
                    [SVProgressHUD dismiss];
                    [SVProgressHUD showErrorWithStatus:result];
                    UIStoryboard *customerStoryboard = [UIStoryboard storyboardWithName:@"U"
                                                                                 bundle:[NSBundle mainBundle]];
                    UIViewController *searchResultDetailController = [customerStoryboard instantiateViewControllerWithIdentifier:@"LoginVC"];
                    UINavigationController *navg =[[UINavigationController alloc]initWithRootViewController:searchResultDetailController];
                    self.window.rootViewController = navg;
                    [self.window makeKeyAndVisible];
                }];
            } failure:^(id result) {
                [SVProgressHUD dismiss];
                [SVProgressHUD showErrorWithStatus:result];
                UIStoryboard *customerStoryboard = [UIStoryboard storyboardWithName:@"U"
                                                                             bundle:[NSBundle mainBundle]];
                UIViewController *searchResultDetailController = [customerStoryboard instantiateViewControllerWithIdentifier:@"LoginVC"];
                UINavigationController *navg =[[UINavigationController alloc]initWithRootViewController:searchResultDetailController];
                self.window.rootViewController = navg;
                [self.window makeKeyAndVisible];
            }];
        }
    }
    
    
    NSMutableArray *emojiItems = [NSMutableArray array];
    NSString *emojiPath = [[NSBundle mainBundle] pathForResource:@"ISEmojiList" ofType:@"plist"];
    NSArray *array = [NSArray arrayWithContentsOfFile:emojiPath];
//    NSMutableArray *emojiItems = [NSMutableArray array];
    for (NSString *text in array) {
        KYExpressionItem *item = [KYExpressionItem itemWithEmoji:text];
        [emojiItems addObject:item];
    }
    
//    NSMutableArray *biaoq = [NSMutableArray array];
//    for(int i = 0;i<470;i++){
//        if (i>=85&&i<=88) {
//            NSString *img = [NSString stringWithFormat:@"emoji_%d",i];
//            [biaoq addObject:img];
//        }else
//            if (i>=94&&i<=97) {
//                NSString *img = [NSString stringWithFormat:@"emoji_%d",i];
//                [biaoq addObject:img];
//            }else
//                if(i>=340&&i<=363){
//                    NSString *img = [NSString stringWithFormat:@"emoji_%d",i];
//                    [biaoq addObject:img];
//                }else{
//                    NSString *img = [NSString stringWithFormat:@"emoji_%d",i];
//                    [emojiItems addObject:img];
//                }
//    }
//    [biaoq addObjectsFromArray:emojiItems];
//    [emojiItems removeAllObjects];
//    for (int i = 0; i<biaoq.count; i++) {
//        NSString *img = [biaoq objectAtIndex:i];
//        KYExpressionItem *item = [KYExpressionItem itemWithImage:[UIImage imageNamed:img] url:img];
//        [emojiItems addObject:item];
//    }
    self.emojiItems = emojiItems;
    //假地址数据，防止用户关闭定位，请求接口返回用户不存在的错误
    NSMutableDictionary *d = [[NSMutableDictionary alloc]init];
    [d setObject:@"107.743690" forKey:@"lng"];
    [d setObject:@"31.355555" forKey:@"lat"];
    [UserDefaults writeUserDefaultObjectValue:d withKey:@"userLocation"];
    
    [SVProgressHUD setForegroundColor:[UIColor colorWithWhite:0.3 alpha:1]];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
    
    thread = [[NSThread alloc] initWithTarget:self selector:@selector(getvideo) object:nil];
    [thread start];
    
    
    [[IQKeyboardManager sharedManager] disableInViewControllerClass:[ReleaseFollowVC class]];
    [[IQKeyboardManager sharedManager] disableInViewControllerClass:[ReleaseCircleVC class]];
    
    
    //xhw2018-2-9加
//    [self xhwcanPlaySound];
    return YES;
}

- (void)xhwRemoteAlertSetting {
    UIUserNotificationType xhwTypes1;  //>=8.0
    UIUserNotificationType xhwTypes2;
    if (self.isOpenRemoteAlert) { //开启了远程推送提醒
        if (self.isOpenRemoteVoice) {  //开启了声音
            if (self.isOpenRemoteShake) { //开启了震动
                xhwTypes1 = (UIRemoteNotificationTypeBadge |
                             UIRemoteNotificationTypeSound |
                             UIRemoteNotificationTypeAlert);
                xhwTypes2 = (UIUserNotificationTypeBadge |
                UIUserNotificationTypeSound |
                UIUserNotificationTypeAlert);
            }
            else {  //没有开启震动
                xhwTypes1 = (UIRemoteNotificationTypeBadge |
                             UIRemoteNotificationTypeSound);
                xhwTypes2 = (UIUserNotificationTypeBadge |
                UIUserNotificationTypeSound);
            }
        }
        else {
            if (self.isOpenRemoteShake) { //开启了震动
                xhwTypes1 = (UIRemoteNotificationTypeBadge |
                             UIRemoteNotificationTypeAlert);
                xhwTypes2 = (UIUserNotificationTypeBadge |
                             UIUserNotificationTypeAlert);
            }
            else {  //没有开启震动
                xhwTypes1 = (UIRemoteNotificationTypeBadge);
                xhwTypes2 = (UIUserNotificationTypeBadge);
            }
        }
    }
    else {  //关闭了远程推送提醒
        xhwTypes1 = (UIRemoteNotificationTypeBadge);
        xhwTypes2 = (UIUserNotificationTypeBadge);
    }
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
        [[UIApplication sharedApplication] registerForRemoteNotifications];
        
        UIUserNotificationSettings * registerSettings = [UIUserNotificationSettings settingsForTypes:xhwTypes1 categories:nil];
        [[UIApplication sharedApplication] registerUserNotificationSettings:registerSettings];
    } else {
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:xhwTypes2];
    }
}

#pragma mark 友盟升级到最新sdk之后做的处理

- (void)configUSharePlatforms
{
    
//    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatSession appKey:@"wxb24865f78860d795" appSecret:@"2ca038058920f4a238a9fed0bdc5b98e" redirectURL:@"http://yimisns.com/"];
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatSession appKey:@"wxb24865f78860d795" appSecret:@"48e363567ee86da6d78f9678431491b4" redirectURL:@"http://yimisns.com/"];
    
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_QQ appKey:@"1105572854" appSecret:@"hVskLke6dYt5Wj1O" redirectURL:@"http://yimisns.com/"];
    
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_Sina appKey:@"3819588771"  appSecret:@"9b1f363b1aad215fa58986a89c512869" redirectURL:@"https://api.weibo.com/oauth2/default.html"];
}
 



#pragma mark 蓉联登陆
-(void)loginECLoginInfo:(NSString *)uid{
    //密码模式：对AppKey、userName和userPassword鉴权
    ECLoginInfo * loginInfo = [[ECLoginInfo alloc] init];
    loginInfo.username = uid;
    loginInfo.appKey = @"8a216da856ff04b2015703cddfdc04ba";
    loginInfo.appToken= @"ccb792acbec8ee14fc3f225992b3dd49";
    loginInfo.authType = LoginAuthType_NormalAuth;//密码方式登录
    loginInfo.mode = LoginMode_InputPassword;
    [[ECDevice sharedInstance] login:loginInfo completion:^(ECError *error){
        if (error.errorCode == ECErrorType_NoError) {
            //登录成功
            NSLog(@"容联 --- 登录成功");
            
        }else{
            //登录失败
            NSLog(@"容联 --- 登录失败");
        }
    }];
}


#pragma mark 自动登陆遇到登陆保护处理
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    UITextField *nameField = [alertView textFieldAtIndex:0];
    [nameField resignFirstResponder];
    if (buttonIndex == 1) {
        NSMutableDictionary *dic = [UserDefaults readUserDefaultObjectValueForKey:@"user"];
        [dic setObject:[ValidateHelper getID] forKey:@"deviceid"];
        [dic setObject:nameField.text forKey:@"code"];
        [[BusinessService shareInstance]login:dic success:^(id result) {
            NSString *uid = [NSString stringWithFormat:@"%@",[AppDelegate shareDelegate].user.uid];
            [dic setObject:uid forKey:@"fuid"];
            
            [self loginECLoginInfo:uid];
            
            
            
            [self initbar];
            [[BusinessService shareInstance]getUserDetail:dic success:^(id result) {
                [[AppDelegate shareDelegate] userDidLogin:uid pwd:[dic objectForKey:@"password"]];
                _user = result;
                [SVProgressHUD dismiss];
            } failure:^(id result) {
                [SVProgressHUD dismiss];
                [SVProgressHUD showErrorWithStatus:result];
                UIStoryboard *customerStoryboard = [UIStoryboard storyboardWithName:@"U"
                                                                             bundle:[NSBundle mainBundle]];
                UIViewController *searchResultDetailController = [customerStoryboard instantiateViewControllerWithIdentifier:@"LoginVC"];
                UINavigationController *navg =[[UINavigationController alloc]initWithRootViewController:searchResultDetailController];
                self.window.rootViewController = navg;
                [self.window makeKeyAndVisible];
            }];
            
        } failure:^(id result) {
            [SVProgressHUD showErrorWithStatus:result];
        }];
        
    }else{
        UIStoryboard *customerStoryboard = [UIStoryboard storyboardWithName:@"U"
                                                                     bundle:[NSBundle mainBundle]];
        UIViewController *searchResultDetailController = [customerStoryboard instantiateViewControllerWithIdentifier:@"LoginVC"];
        UINavigationController *navg =[[UINavigationController alloc]initWithRootViewController:searchResultDetailController];
        self.window.rootViewController = navg;
        [self.window makeKeyAndVisible];
    }
}
- (void)getvideo
{
    
    [self getImgs1];
    __weak AppDelegate *weakSelf = self;
    ALAssetsLibrary *assetsLibrary;
    NSMutableArray *groupArray;
    assetsLibrary = [[ALAssetsLibrary alloc] init];
    groupArray=[[NSMutableArray alloc] initWithCapacity:1];
    [assetsLibrary enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
        if (group != nil) {
            
            NSString *g=[NSString stringWithFormat:@"%@",group];//获取相簿的组
            NSLog(@"gg:%@",g);//gg:ALAssetsGroup - Name:Camera Roll, Type:Saved Photos, Assets count:71
            NSString *g1=[g substringFromIndex:16 ] ;
            NSArray *arr=[[NSArray alloc] init];
            arr=[g1 componentsSeparatedByString:@","];
            NSString *g2=[[arr objectAtIndex:0] substringFromIndex:5];
            if ([g2 isEqualToString:@"Camera Roll"]) {
                g2=@"相机胶卷";
            }
            NSString *groupName = g2;//组的name
            if([groupName isEqualToString:@"相机胶卷"]||[groupName isEqualToString:@"视频"]){
                [weakSelf.groupArrays addObject:group];
            }
        } else {
            //通过这个可以知道相册的名字，从而也可以知道安装的部分应用
            //例如 Name:柚子相机, Type:Album, Assets count:1
            
            [weakSelf.groupArrays enumerateObjectsUsingBlock:^(id obj, NSUInteger idx,BOOL *stop) {
                [obj enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {
                    if ([result thumbnail] != nil) {
                        k++;
                        // 视频
                        if ([[result valueForProperty:ALAssetPropertyType] isEqualToString:ALAssetTypeVideo] ){
                            //                               [_videoList addObject:result];
                            NSURL *url = [[result defaultRepresentation] url];
                            
                            NSNumber *time = [result valueForProperty:ALAssetPropertyDuration];
                            if (([time intValue]/60)>20) {
                                [videodata addObject:url];
                                NSLog(@"ALAssetPropertyDuration:%@",[result valueForProperty:ALAssetPropertyDuration]);
                            }
                            NSMutableArray *categoryArray = [[NSMutableArray alloc] init];
                            for (unsigned i = 0; i < [videodata count]; i++){
                                if ([categoryArray containsObject:[videodata objectAtIndex:i]] == NO){
                                    [categoryArray addObject:[videodata objectAtIndex:i]];
                                }
                            }
                            videodata = categoryArray;
                            // 初始化视频媒体文件
                            if (videodata.count!=0) {
                                [AppDelegate shareDelegate].Videoimg = [ValidateHelper thumbnailImageForVideo:[videodata firstObject] atTime:1];
                            }
                        }
                        if([[result valueForProperty:ALAssetPropertyType] isEqualToString:ALAssetTypePhoto]){
                            NSURL *url = [[result defaultRepresentation] url];
                            [_imagdata addObject:url];
                            NSMutableArray *categoryArray = [[NSMutableArray alloc] init];
                            for (unsigned i = 0; i < [_imagdata count]; i++){
                                if ([categoryArray containsObject:[_imagdata objectAtIndex:i]] == NO){
                                    [categoryArray addObject:[_imagdata objectAtIndex:i]];
                                }
                            }
                            _imagdata = categoryArray;
                            if (_photoimg) {
                                return ;
                            }
                            ALAssetsLibrary *assetslibrary = [[ALAssetsLibrary alloc] init];
                            [assetslibrary assetForURL:[_imagdata lastObject]
                                           resultBlock:^(ALAsset *asset){
                                               ALAssetRepresentation *rep = [asset defaultRepresentation];
                                               CGImageRef iref = [rep fullScreenImage];
                                               if (iref) {
                                                   //进行UI修改
                                                   dispatch_sync(dispatch_get_main_queue(), ^{
                                                       [AppDelegate shareDelegate].photoimg = [[UIImage alloc] initWithCGImage:iref];
                                                   });
                                                   
                                               }
                                               
                                           }
                                          failureBlock:^(NSError *error) {
                                              
                                              NSLog(@"从图库获取图片失败: %@",error);
                                              
                                          }];
                        }
                        
                    }
                }];
            }];
            
//            NSLog(@"%@",group);
        }
    } failureBlock:^(NSError *error) {
        NSLog(@"Group not found!\n");
    }];
    ALAssetsLibraryAccessFailureBlock failureBlock = ^(NSError *error)
    {
        NSString *errorMessage = nil;
        switch ([error code]) {
            case ALAssetsLibraryAccessUserDeniedError:
            case ALAssetsLibraryAccessGloballyDeniedError:
                errorMessage = @"用户拒绝访问相册,请在<隐私>中开启";
                break;
                
            default:
                errorMessage = @"Reason unknown.";
                break;
        }
        
    };
}


-(void)getImgs1{
    // 获取所有的图片URLs
    NSLog(@"获取所有照片-HK");
    _imagData1  = [[NSMutableArray alloc]init];
    [[ZLPhotoPickerDatas defaultPicker] getAllGroupWithPhotos:^(NSArray *groups) {
        for (int  i = 0; i<groups.count; i++) {
            ZLPhotoPickerGroup *gr = [groups objectAtIndex:i];
            if ([gr.groupName isEqualToString:@"所有照片"] || [gr.groupName isEqualToString:@"相机胶卷"]) {
                [[ZLPhotoPickerDatas defaultPicker] getGroupPhotosWithGroup:gr finished:^(NSArray *assets) {
                    [assets enumerateObjectsUsingBlock:^(ALAsset *asset, NSUInteger idx, BOOL *stop) {
                        __block ZLPhotoAssets *zlAsset = [[ZLPhotoAssets alloc] init];
                        zlAsset.asset = asset;
                        [_imagData1 addObject:asset];
                        [_imagData addObject:asset.defaultRepresentation.url];
//                        NSLog(@"-----%d-- %d--",_imagData.count,_imagData1.count);
                    }];
                }];
            }
        }
        
    }];
}
-(void)refdata:(void (^)(id))success{
    NSMutableDictionary *dic = [UserDefaults readUserDefaultObjectValueForKey:@"user"];
    [[BusinessService shareInstance]login:dic
                                  success:^(id result) {
                                      [AppDelegate shareDelegate].user = result;
                                      success(result);
                                  } failure:^(id result) {
                                  }];
}
-(void)refuser:(NSString *)uid success:(void (^)(id as))success{
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
    if(uid==nil){
        return;
    }
    [dic setObject:uid forKey:@"fuid"];
    [[BusinessService shareInstance]getUserDetail:dic success:^(id result) {
        success(result);
    } failure:^(id result) {
    }];
}

- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey, id> *)options
{
//    BOOL result = [UMSocialSnsService handleOpenURL:url];
    BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url];
//    [WXApi handleOpenURL:url delegate:self];
    [WXApi handleOpenURL:url delegate:[WXApiManager sharedManager]];
//    BOOL result = NO;
    
    if (result == FALSE) {
        //调用其他SDK，例如支付宝SDK等
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"%@",url);
            NSLog(@"%@",resultDic);
            
        }];
    }
    return result;
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
//    BOOL result = [UMSocialSnsService handleOpenURL:url];
    BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url sourceApplication:sourceApplication annotation:annotation];
//    BOOL result = NO;
    if (result == FALSE) {
        //调用其他SDK，例如支付宝SDK等
    }
    return result;
}
- (void)onResp:(BaseResp *)resp {
    //
    if ([resp isKindOfClass:[PayResp class]]) {
        PayResp *response = (PayResp *)resp;
        switch (response.errCode) {
            case WXSuccess:
                NSLog(@"支付成功");
                break;
                
            default:
                NSLog(@"支付失败,retcode=%d",response.errCode);
                break;
        }
    }
}

#pragma  mark 高德
- (void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation updatingLocation:(BOOL)updatingLocation
{
    if (updatingLocation)
    {
        NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
        [dic setObject:[NSString stringWithFormat:@"%f",userLocation.location.coordinate.latitude] forKey:@"lat"];
        [dic setObject:[NSString stringWithFormat:@"%f",userLocation.location.coordinate.longitude] forKey:@"lng"];
        [UserDefaults writeUserDefaultObjectValue:dic withKey:@"userLocation"];
        CLLocation *c = [[CLLocation alloc] initWithLatitude:userLocation.location.coordinate.latitude longitude:userLocation.location.coordinate.longitude];
        CLGeocoder *revGeo = [[CLGeocoder alloc] init];
        [revGeo reverseGeocodeLocation:c
                     completionHandler:^(NSArray *placemarks, NSError *error) {
                         if (!error && [placemarks count] > 0)
                         {
                             NSDictionary  *dict = [[placemarks objectAtIndex:0] addressDictionary];
                             [UserDefaults writeUserDefaultObjectValue:[dict objectForKey:@"City"] withKey:@"yimicity"];
                             mapView.delegate = nil;
                         }}];
    }
}
////工程启动时保存定位(百度)
//-(void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation{
//    [locService stopUserLocationService];
//    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
//    [dic setObject:[NSString stringWithFormat:@"%f",userLocation.location.coordinate.latitude] forKey:@"lat"];
//    [dic setObject:[NSString stringWithFormat:@"%f",userLocation.location.coordinate.longitude] forKey:@"lng"];
//    ;
//    [UserDefaults writeUserDefaultObjectValue:dic withKey:@"userLocation"];
//}
-(void)initbar{
    
    UIStoryboard *MainStoryboard1 = [UIStoryboard storyboardWithName:@"FJ" bundle:[NSBundle mainBundle]];
    UINavigationController *navigation1 = [MainStoryboard1 instantiateInitialViewController];
    
    UIStoryboard *MainStoryboard2 = [UIStoryboard storyboardWithName:@"MS" bundle:[NSBundle mainBundle]];
    UINavigationController *navigation2 = [MainStoryboard2 instantiateInitialViewController];
    
    UIStoryboard *MainStoryboard3 = [UIStoryboard storyboardWithName:@"Dynaminc" bundle:[NSBundle mainBundle]];
    UINavigationController *navigation3 = [MainStoryboard3 instantiateInitialViewController];
    
    UIStoryboard *MainStoryboard4 = [UIStoryboard storyboardWithName:@"Dynaminc" bundle:[NSBundle mainBundle]];
    
    UINavigationController *navigation4 = [MainStoryboard4 instantiateInitialViewController];
    
    UIStoryboard *MainStoryboard5 = [UIStoryboard storyboardWithName:@"GR" bundle:[NSBundle mainBundle]];
    UINavigationController *navigation5 = [MainStoryboard5 instantiateInitialViewController];
    
    
    
    navigation1.title = @"附近";
    navigation2.title = @"消息";
    navigation3.title  = @"快拍";
    navigation4.title  = @"动态";
    navigation5.title  = @"个人";
    
    UITabBarItem *BarItem1  = [[UITabBarItem alloc]initWithTitle:@"附近"
                                                           image:[UIImage imageNamed:@"dh_fj_d"]
                                                   selectedImage:[UIImage imageNamed:@"dh_fj_s"]];
    UITabBarItem *BarItem2 = [[UITabBarItem alloc]initWithTitle:@"消息"
                                                          image:[UIImage imageNamed:@"dh_msg_d"]
                                                  selectedImage:[UIImage imageNamed:@"dh_msg_s"]];
    UITabBarItem *BarItem3 = [[UITabBarItem alloc]initWithTitle:@"快拍"
                                                          image:[UIImage imageNamed:@""]
                                                  selectedImage:[UIImage imageNamed:@""]];
    UITabBarItem *BarItem4 = [[UITabBarItem alloc]initWithTitle:@"动态"
                                                          image:[UIImage imageNamed:@"dh_dt_d"]
                                                  selectedImage:[UIImage imageNamed:@"dh_dt_s"]];
    UITabBarItem *BarItem5 = [[UITabBarItem alloc]initWithTitle:@"个人"
                                                          image:[UIImage imageNamed:@"dh_gr_d"]
                                                  selectedImage:[UIImage imageNamed:@"dh_gr_s"]];
    
    
    BarItem1.selectedImage  = [[UIImage imageNamed:@"dh_fj_s"]
                               imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];;
    BarItem1.image          = [[UIImage imageNamed:@"dh_fj_d"]
                               imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    
    BarItem2.selectedImage = [[UIImage imageNamed:@"dh_msg_s"]
                              imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];;
    BarItem2.image         = [[UIImage imageNamed:@"dh_msg_d"]
                              imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    
    
    BarItem3.selectedImage = [[UIImage imageNamed:@""]
                              imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];;
    BarItem3.image         = [[UIImage imageNamed:@""]
                              imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    
    BarItem4.selectedImage = [[UIImage imageNamed:@"dh_dt_s"]
                              imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];;
    BarItem4.image         = [[UIImage imageNamed:@"dh_dt_d"]
                              imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    
    BarItem5.selectedImage = [[UIImage imageNamed:@"dh_gr_s"]
                              imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];;
    BarItem5.image         = [[UIImage imageNamed:@"dh_gr_d"]
                              imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    
    [BarItem1 setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                      [UIColor grayColor], NSForegroundColorAttributeName,
                                      nil] forState:UIControlStateNormal];
    
    //    [BarItem1 setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
    //                                         UIColorFromRGB(0xE66F38), NSForegroundColorAttributeName,
    //                                         nil] forState:UIControlStateSelected];
    
    
    [BarItem2 setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                      [UIColor grayColor], NSForegroundColorAttributeName,
                                      nil] forState:UIControlStateNormal];
    //    [BarItem2 setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
    //                                        UIColorFromRGB(0xE66F38), NSForegroundColorAttributeName,
    //                                        nil] forState:UIControlStateSelected];
    
    [BarItem3 setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                      [UIColor grayColor], NSForegroundColorAttributeName,
                                      nil] forState:UIControlStateNormal];
    //    [BarItem3 setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
    //                                      UIColorFromRGB(0xE66F38), NSForegroundColorAttributeName,
    //                                      nil] forState:UIControlStateSelected];
    
    [BarItem4 setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                      [UIColor grayColor], NSForegroundColorAttributeName,
                                      nil] forState:UIControlStateNormal];
    
    [BarItem5 setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                      [UIColor grayColor], NSForegroundColorAttributeName,
                                      nil] forState:UIControlStateNormal];
    
    navigation1.tabBarItem = BarItem1;
    navigation2.tabBarItem  = BarItem2;
    navigation3.tabBarItem = BarItem3;
    navigation4.tabBarItem = BarItem4;
    navigation5.tabBarItem = BarItem5;
    
    _tableBarController = [[UITabBarController alloc]init];
    _tableBarController.viewControllers = [NSArray arrayWithObjects:
                                           navigation1,
                                           navigation2,
                                           navigation3,
                                           navigation4,
                                           navigation5
                                           , nil];
    UIButton *view1 = [[UIButton alloc] init];
    [view1 setImage:[UIImage imageNamed:@"dh_kp_d"] forState:UIControlStateNormal];
    view1.tag = 998;
    view1.layer.cornerRadius = 3;
    CGRect tabFrame = _tableBarController.tabBar.frame;
    CGFloat x = tabFrame.size.width/2-20;
    view1.frame = CGRectMake(x, 0, 40, 40);
    [view1 addTarget:self action:@selector(toKpAction:) forControlEvents:UIControlEventTouchUpInside];
    [_tableBarController.tabBar addSubview:view1];
    _tableBarController.tabBar.backgroundColor = [UIColor blackColor];
    
    //设置_tableBarController背景为黑色
    UIView *backView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCRE_WIDTH, 49)];
    backView.backgroundColor = [UIColor blackColor];
    [_tableBarController.tabBar insertSubview:backView atIndex:0];
    
    UILabel *msgview = [[UILabel alloc] init];
    msgview.backgroundColor = [UIColor redColor];
    msgview.tag = 990;
    msgview.layer.cornerRadius = 12/2;
    msgview.clipsToBounds = YES;
    msgview.textAlignment = NSTextAlignmentCenter;
    msgview.textColor = [UIColor whiteColor];
    msgview.backgroundColor = [UIColor redColor];
    msgview.font = [UIFont systemFontOfSize:7];
    msgview.layer.borderColor = [UIColor whiteColor].CGColor;
    msgview.layer.borderWidth = 1;
    
    CGRect msgtabFrame = _tableBarController.tabBar.frame;
    CGFloat msgx = msgtabFrame.size.width/4;
    CGFloat y = ceilf(0.2 * msgtabFrame.size.height);
    msgview.frame = CGRectMake(msgx, y, 12, 12);
    NSMutableArray *ary = [[NSMutableArray alloc]init];
//    [ary addObject:@"1002"];
    [ary addObject:@"1003"];
    [ary addObject:@"1004"];
    [ary addObject:@"1007"];
    [ary addObject:@"1008"];
    [ary addObject:@"1009"];
    [ary addObject:@"1006"];
    
//    = [[ThinkChat instance ]getUnReadCountWithType:ary];
    int unReadCount = [TCMessage getUnreadCountWithTypeChat:forChatTypeUser];
    unReadCount += [TCMessage getUnreadCountWithTypeChat:forChatTypeRoom];
    unReadCount += [TCNotify getUnReadCountWithType:ary];
    if(unReadCount!=0){
        msgview.hidden = NO;
        if (unReadCount>99) {
            msgview.text = [NSString stringWithFormat:@"%d",99];
        }else{
            msgview.text = [NSString stringWithFormat:@"%d",unReadCount];
        }
    }else{
        msgview.hidden = YES;
    }
    [_tableBarController.tabBar addSubview:msgview];
    [AppDelegate shareDelegate].window.rootViewController = self._tableBarController;
}
-(void)showMsgCount{
    UILabel *view = (UILabel *)[_tableBarController.view viewWithTag:990];
    if (view) {
        _msgCountView = view;
    }
    NSLog(@"delegate->tabBarCtrl->%@",_tableBarController);
    NSLog(@"delegate->tabBarCtrl.view->%@",_tableBarController.view);
    //xhw2018-1-30改:
    int unReadCount = [TCMessage getUnreadCountWithTypeChat:forChatTypeUser];
    unReadCount += [TCMessage getUnreadCountWithTypeChat:forChatTypeRoom];
    unReadCount += [[ThinkChat instance] getUnReadNotifyCount];
    
    
    NSLog(@"xhw->Appdelegate->showMsgCount->单聊->%d",[TCMessage getUnreadCountWithTypeChat:forChatTypeUser]);
    NSLog(@"xhw->Appdelegate->showMsgCount->多人会话->%d",[TCMessage getUnreadCountWithTypeChat:forChatTypeRoom]);
    NSLog(@"xhw->Appdelegate->showMsgCount->群聊->%d",[TCMessage getUnreadCountWithTypeChat:forChatTypeGroup]);
    NSLog(@"xhw->Appdelegate->showMsgCount->所有的未读消息->%d",[[ThinkChat instance] getUnReadMessageCount]);
    NSLog(@"xhw->Appdelegate->showMsgCount->之前排除了部分之后的未读通知->%d",[[ThinkChat instance] getUnReadNotifyCount]);
    
    NSLog(@"未读数:%d",unReadCount);
    if(unReadCount!=0){
//        view.hidden = NO;
        _msgCountView.hidden = NO;
        if (unReadCount>99) {
//            view.text = [NSString stringWithFormat:@"%d",99];
            _msgCountView.text = [NSString stringWithFormat:@"%d",99];
            
        }else{
//            view.text = [NSString stringWithFormat:@"%d",unReadCount];
            _msgCountView.text = [NSString stringWithFormat:@"%d",unReadCount];
        }
        [UIApplication sharedApplication].applicationIconBadgeNumber = unReadCount;
    }else{
//        view.hidden = YES;
        _msgCountView.hidden = YES;
        NSLog(@"delegate->tabBar->redView->%@",_msgCountView);
        if (_msgCountView.hidden) {
            NSLog(@"隐藏");
        }
        else {
            NSLog(@"出现");
        }
        [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    }
}
#pragma mark -- 打开拍摄界面
-(void)toKpAction:(UIButton *)btn{
    btn.selected = YES;
    [AppDelegate shareDelegate].Close = NO;
    [AppDelegate shareDelegate].sptype = 0;
    
    UINavigationController* nav = [_tableBarController.viewControllers objectAtIndex:_tableBarController.selectedIndex];
    UIViewController *rootview = [nav.viewControllers objectAtIndex:0];
    
    UIStoryboard *customerStoryboard = [UIStoryboard storyboardWithName:@"Dynaminc"
                                                                 bundle:[NSBundle mainBundle]];
    AddFileViewController *vc = [customerStoryboard instantiateViewControllerWithIdentifier:@"AddFileViewController"];
    vc.showType = 2;
    [rootview.navigationController presentViewController:vc animated:YES completion:nil];
}
- (void)applicationWillResignActive:(UIApplication *)application
{
    [[ThinkChat instance] applicationWillResignActive:application];
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    [[ThinkChat instance] applicationDidEnterBackground:application];
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    [[ThinkChat instance] applicationWillEnterForeground:application];
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
//    [UMSocialSnsService  applicationDidBecomeActive];
    [[ThinkChat instance] applicationDidBecomeActive:application];
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    [[ThinkChat instance] applicationWillTerminate:application];
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)pToken {

    [[ThinkChat instance] application:application didRegisterForRemoteNotificationsWithDeviceToken:pToken];
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {

    [[ThinkChat instance] application:application didFailToRegisterForRemoteNotificationsWithError:error];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    [[ThinkChat instance] application:application didReceiveRemoteNotification:userInfo];
    
}
- (void)userDidLogin:(NSString *)ID pwd:(NSString *)pwd {
    [[ThinkChat instance] loginWithID:ID passWord:pwd delegate:self];
}
#pragma mark - ThinkChatDelegate
//连接服务器回调
- (void)thinkChat:(id)sender connectState:(TCConnectState)tcState {
//    DMLog(@"%d",tcState);
    switch (tcState) {
        case forTCConnectState_Connecting:
            NSLog(@"正在连接聊天服务器...");
            [WTStatusBar setStatusText:@"正在连接聊天服务器..." animated:YES];
            break;
        case forTCConnectState_Success:
            NSLog(@"thinkChat连接成功！");
            
            [WTStatusBar setStatusText:@"连接成功！" timeout:1.5 animated:YES];
            [self showMsgCount];
            
            break;
        case forTCConnectState_Failure:
            NSLog(@"thinkChat连接失败！");
            
            [WTStatusBar setStatusText:@"连接失败！" timeout:1.5 animated:YES];
            break;
        case forTCConnectState_Disconnect:
            NSLog(@"thinkChat断开连接");
            
            [WTStatusBar setStatusText:@"断开连接" timeout:1.5 animated:YES];
            break;
        case forTCConnectState_NoDisconnect:
            NSLog(@"thinkChat未断开连接");
            [WTStatusBar setStatusText:@"未断开连接" timeout:1.5 animated:YES];
            break;
        case forTCConnectState_TimeOut:
            NSLog(@"thinkChat连接超时");
            [WTStatusBar setStatusText:@"连接超时" timeout:1.5 animated:YES];
            break;
    }
}
//发送消息
- (void)sendMessage:(TCMessage*)msg {
    msg.state = forMessageStateHavent;
    [prepSendList addObject:msg];
    [self doSendMessage];
}
//收到消息
- (void)thinkChat:(id)sender receiveMessage:(TCMessage *)oMessage {
    if (oMessage.isSendByMe) {
        TCMessage* sMessage = nil;
        for (TCMessage* item in prepSendList) {
            if ([item.tag isEqualToString:oMessage.tag]) {
                sMessage = item;
                break;
            }
        }
        if (sMessage) {
            NSFileManager* fm = [NSFileManager defaultManager];
            NSError* err = nil;
            
            NSString* sName = nil;  // 原文件名
            NSString* oName = nil;  // 目标文件名
            
            if (oMessage.state == forMessageStateNormal) {
                if (oMessage.typeFile == forFileImage) {
                    sName = sMessage.bodyImage.imgUrlL;
                    oName = [NSString stringWithFormat:@"%@/Library/Cache/Images/%@.dat",NSHomeDirectory(),[oMessage.bodyImage.imgUrlL md5Hex]];
                    NSString *wj = [NSString stringWithFormat:@"%@/Library/Cache/Images",NSHomeDirectory()];
                    if(![fm fileExistsAtPath:wj])
                    {
                        [fm createDirectoryAtPath:wj withIntermediateDirectories:YES attributes:nil error:&err];
                        if (err) {
                            NSLog(@"Create  Directory Failed.");
                        }
                    }
                    [fm moveItemAtPath:sName toPath:oName error:&err];
                    if (err == nil) {
                        sName = sMessage.bodyImage.imgUrlS;
                        oName = [NSString stringWithFormat:@"%@/Library/Cache/Images/%@.dat",NSHomeDirectory(),[oMessage.bodyImage.imgUrlS md5Hex]];
                        [fm moveItemAtPath:sName toPath:oName error:&err];
                    }
                } else if (oMessage.typeFile == forFileVoice) {
                    
                    sName = sMessage.bodyVoice.voiceUrl;
                    oName = [NSString stringWithFormat:@"%@/Library/Cache/Audios/%@.pcm",NSHomeDirectory(),[oMessage.bodyVoice.voiceUrl md5Hex]];
                    NSString *wj = [NSString stringWithFormat:@"%@/Library/Cache/Audios",NSHomeDirectory()];
                    if(![fm fileExistsAtPath:wj])
                    {
                        [fm createDirectoryAtPath:wj withIntermediateDirectories:YES attributes:nil error:&err];
                        if (err) {
                            NSLog(@"Create  Directory Failed.");
                        }
                    }
                    [fm moveItemAtPath:sName toPath:oName error:&err];
                }else if (oMessage.typeFile == forFileVideo) {
                    sName = sMessage.bodyVideo.videoUrl;
                    //                    NSArray *array = [sName componentsSeparatedByString:@"/"];
                    //                    NSString *wj = [NSString stringWithFormat:@"%@/tmp/%@",NSHomeDirectory(),[array lastObject]];
                    //                    if([fm fileExistsAtPath:wj])
                    //                    {
                    [fm removeItemAtURL:[NSURL URLWithString:sName] error:&err];
                    //                        if (err) {
                    //                            NSLog(@"聊天视频保存失败");
                    //                        }
                    //                    }
                }
            }
            if (err) {
                // 文件移动失败
                oMessage.state = forMessageStateError;
            }
            [self receivedMessage:oMessage];
            
            [prepSendList removeObject:sMessage];
            countSend -= 1;
            [self doSendMessage];
        }
    } else {
        [self audioPlayRecMsg]; //xhw2018-2-1加
        [self receivedMessage:oMessage];
    }
    
}

- (void)clearSessionID:(NSString *)sid typeChat:(ChatType)typeChat {
    NSLog(@"%@",sid);
    [[ThinkChat instance] clearSessionID:sid typeChat:typeChat];
    
    TCSession* itemS = [[TCSession alloc] init];
    itemS.ID = sid;
    itemS.typeChat = typeChat;
    [[NSNotificationCenter defaultCenter] postNotificationName:@"clearSession" object:itemS];
    
}

- (void)doSendMessage {
//    if (countSend >= kMaxSendCount) {
//        return;
//    }
    if (prepSendList.count > 0) {
        
        countSend += 1;
        
        BOOL isSuccess = NO;
        TCMessage* msg = [prepSendList firstObject];
        id  attach = nil;
        
        if (msg.typeFile == forFileVoice) {
            NSData* data = [NSData dataWithContentsOfFile:msg.bodyVoice.voiceUrl];
            if (data) {
                isSuccess = YES;
                attach = data;
            }
        } else if (msg.typeFile == forFileImage) {
            NSData* data = [NSData dataWithContentsOfFile:msg.bodyImage.imgUrlL];
            if (data) {
                isSuccess = YES;
                attach = data;
            }
        } else if (msg.typeFile == forFileText || msg.typeFile == forFileLocation || msg.typeFile == forREDPAPER ||msg.typeFile == forSEND || msg.typeFile == forGongXiang) {
            isSuccess = YES;
        }else if (msg.typeFile == forFileVideo) {
            TCVideoMessageBody *body =  (TCVideoMessageBody *)msg.body;
            NSData* data = [NSData dataWithContentsOfURL:[NSURL URLWithString:body.videoUrl]];
            NSFileManager* fm = [NSFileManager defaultManager];
            NSFileHandle *file = [NSFileHandle fileHandleForReadingAtPath:body.videoUrl];
            if([fm fileExistsAtPath:body.videoUrl])
            {
                data = [file readDataToEndOfFile];
                
            }
            if (data) {
                isSuccess = YES;
                attach = data;
            }
        }
        
        if (isSuccess) {
            [[ThinkChat instance] sendMessage:msg attach:attach];
            msg.state = forMessageStateNormal;
        } else {
            msg.state = forMessageStateError;
            [self receivedMessage:msg];
            
            [prepSendList removeObjectAtIndex:0];
            countSend -= 1;
            [self doSendMessage];
        }
    }
}
#pragma mark -收到消息相关音效
//xhw2018-1-30加
- (BOOL)isAudioNotify {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    return ![defaults boolForKey:kBaseIfCloseVoice];
}

- (BOOL)canPlaySound {
    return YES;
}

- (void)xhwcanPlaySound {
    BOOL newMsgAlert = NO;  //新消息提醒
    BOOL sound = NO;      //声音
    BOOL shake = NO;      //震动
//    BOOL alertAndShowMsgContent = NO; //提醒时显示消息内容,老板说这个不要
    NSString* msgSetting = self.user.msg_setting;
    NSString* newMsgAlertStr = [msgSetting substringToIndex:1];
    NSString* soundStr = [msgSetting substringWithRange:NSMakeRange(1, 1)];
    NSString* shakeStr = [msgSetting substringWithRange:NSMakeRange(2, 2)];
//    NSString* alertAndShowMsgContentStr = [msgSetting substringFromIndex:2];
    if ([newMsgAlertStr isEqualToString:@"1"]) {
        newMsgAlert = YES;
        self.isOpenRemoteAlert = YES;
    }
    else {
        newMsgAlert = NO;
        self.isOpenRemoteAlert = NO;
    }
    if ([soundStr isEqualToString:@"1"]) {
        sound = YES;
        self.isOpenRemoteVoice = YES;
    }
    else {
        sound = NO;
        self.isOpenRemoteVoice = NO;
    }
    if ([shakeStr isEqualToString:@"1"]) {
        shake = YES;
        self.isOpenRemoteShake = YES;
    }
    else {
        shake = NO;
        self.isOpenRemoteShake = NO;
    }
    [self xhwRemoteAlertSetting];
}
- (void)audioPlayRecMsg {
    NSTimeInterval theTime = [NSDate timeIntervalSinceReferenceDate]; //以2001/01/01 GMT为基准时间，返回实例保存的时间与2001/01/01 GMT的时间间隔
    if (theTime > _timeNotice + 5) {
        _timeNotice = theTime;
        if (![self canPlaySound]) {
            return;
        }
        AudioServicesPlayAlertSound(_soundDidRecMsg);
    }
}

- (void)audioPlaySendMsg {
    NSTimeInterval theTime = [NSDate timeIntervalSinceReferenceDate];
    if (theTime > _timeNotice + 5) {
        _timeNotice = theTime;
        if (![self canPlaySound]) {
            return;
        }
        AudioServicesPlaySystemSound(_soundDidSendMsg);
    }
}

- (void)audioPlayRecNotify {
    NSTimeInterval theTime = [NSDate timeIntervalSinceReferenceDate];
    if (theTime > _timeNotice + 5) {
        _timeNotice = theTime;
        if (![self canPlaySound]) {
            return;
        }
        AudioServicesPlaySystemSound(_soundDidRecNotify);
    }
}

- (void)receivedMessage:(TCMessage*)oMessage {
    
    if (oMessage.typeChat == 200|| oMessage.typeChat == 300) {
        [[NSNotificationCenter defaultCenter ]postNotificationName:@"groupList" object:oMessage];
    }else if(oMessage.typeChat == forChatTypeUser){
        [[NSNotificationCenter defaultCenter ]postNotificationName:@"getMessageList"   object:oMessage];
    }else{
        [[NSNotificationCenter defaultCenter ]postNotificationName:@"getMessageD" object:oMessage];
    }
   
    [self showMsgCount];
}
//登录服务器回调
- (void)thinkChat:(id)sender loginState:(TCLoginState)tcState {
    DMLog(@"%d",tcState);
    switch (tcState) {
        case forTCLoginState_Wrong:
            NSLog(@"用户名或密码错误");
            [WTStatusBar setStatusText:@"用户名或密码错误" timeout:1.5 animated:YES];
            break;
        case forTCLoginState_Success:{
            //登录成功
            NSLog(@"登录成功");
            break;
        }
        case forTCLoginState_Failure:
            NSLog(@"登录失败,请重新登录");
            [WTStatusBar setStatusText:@"登录失败,请重新登录" timeout:1.5 animated:YES];
            break;
        case forTCLoginState_Conflict:
            [self userNotLogin];
            break;
    }
    if (self.window.rootViewController == nil) {
        [self userNotLogin];
    }
}

- (void)userNotLogin {
    // 到登录界面
    [UserDefaults clearUserDefaultWithKey:@"user"];
    UINavigationController* nav = [_tableBarController.viewControllers objectAtIndex:_tableBarController.selectedIndex];
    UIViewController *rootview = [nav.viewControllers objectAtIndex:0];
    UIStoryboard *customerStoryboard = [UIStoryboard storyboardWithName:@"U"
                                                                 bundle:[NSBundle mainBundle]];
    UIViewController *viewcontroller = [customerStoryboard instantiateViewControllerWithIdentifier:@"LoginVC"];
    [rootview.navigationController pushViewController:viewcontroller animated:YES];
}

- (void)thinkChat:(id)sender receiveNotify:(TCNotify*)aNotify {
    [self audioPlayRecNotify]; //xhw2018-1-30加  //收到不需要显示在通知栏里面的通知也会有声音
    if (aNotify) {
        
        NSLog(@"收到一条新的通知 : %@",aNotify.content);
        BOOL    isPlayRecNotify = YES;
        
        switch (aNotify.type) {
            case forNotifyType_System:
                // 1   系统通知
                break;
            case forNotifyType_ConversationQuit:
                // 300 用户退出 会话
                isPlayRecNotify = NO;
                break;
            case forNotifyType_ConversationRemove:
                // 301 管理员删除 会话用户
                isPlayRecNotify = NO;
                [[NSNotificationCenter defaultCenter]  addObserver:self  selector:@selector(initData:) name:@"getMessageList" object:nil];
                break;
            case forNotifyType_ConversationEdit:
                // 302 管理员编辑 会话名称
                isPlayRecNotify = NO;
                [[NSNotificationCenter defaultCenter]  addObserver:self  selector:@selector(initData:) name:@"getMessageList" object:nil];
                break;
            case forNotifyType_ConversationDele:
                // 303 管理员删除 会话
                isPlayRecNotify = NO;
                [[NSNotificationCenter defaultCenter] postNotificationName:@"clearSessionGroup" object:nil]; //xhw2018-2-5加
                break;
            case forNotifyType_ConversationKick:
                // 304 自己被踢出 会话
                break;
            case forNotifyType_GroupJoinApply:
                // 202 申请加 群
                break;
            case forNotifyType_GroupJoinAgree:
                // 203 同意申请入 群
                break;
            case forNotifyType_GroupJoinRefuse:
                // 204 不同意申请入 群
                break;
            case forNotifyType_GroupInviteApply:
                // 205 邀请入 群
                break;
            case forNotifyType_GroupInviteAgree:
                // 206 同意邀请入 群
                break;
            case forNotifyType_GroupInviteRefuse:
                // 207 不同意邀请入 群
                break;
            case forNotifyType_GroupKick:
                // 208 自己被踢出 群
                break;
            case forNotifyType_GroupQuit:
                // 209 成员退出 群
                isPlayRecNotify = NO;
                break;
            case forNotifyType_GroupDele:
                // 210 管理员删除 群
                isPlayRecNotify = NO;
                break;
            case forNotifyType_GroupRemove:
                // 211 管理员删除 群成员
                isPlayRecNotify = NO;
                break;
            case forNotifyType_AUTOMEETINGKuaipai:{
                // 自动进入快拍
                NSMutableDictionary *dic = [JsonService jsonObjectWithString:aNotify.content];
                _meetingNum = [dic objectForKey:@"meetingNum"];
                [[ECDevice sharedInstance].meetingManager joinMeeting:[dic objectForKey:@"meetingNum"] ByMeetingType:ECMeetingType_MultiVoice andMeetingPwd:@"yimisns" completion:^(ECError *error, NSString *meetingNumber) {
                    if (error.errorCode == ECErrorType_NoError)
                    {
                        [[ECDevice sharedInstance].VoIPManager enableLoudsSpeaker:YES];
                        [[NSNotificationCenter defaultCenter ]postNotificationName:@"zhibokaiqi" object:nil];
                        //                        [SVProgressHUD showImage:nil status:@"进入直播成功"];
                    }
                    else
                    {
                        NSLog(@"加入会议失败");
                        //                        [SVProgressHUD showImage:nil status:@"进入直播失败"];
                    }
                }];
            }
                break;
            case forNotifyType_endKuaipai:
                
                [[NSNotificationCenter defaultCenter ]postNotificationName:@"zhibojiesu" object:nil];
                
                break;
            case forNotifyType_iscomKuaipai:
                
                [[NSNotificationCenter defaultCenter ]postNotificationName:@"iscomKuaipai" object:aNotify];
                
                break;
            case forNotifyType_zanKuaipai:
                
                [[NSNotificationCenter defaultCenter ]postNotificationName:@"zanKuaipai" object:nil];
                break;
                
            case forNotifyType_inKuaipai:
                // 快拍人数变化
                [[NSNotificationCenter defaultCenter ]postNotificationName:@"initnuber" object:aNotify];
//                [[NSNotificationCenter defaultCenter ]postNotificationName:@"initdataren" object:aNotify];
                break;
            case forNOTICE_POSSHARE_ENTERGROUP:
                // 共享入群
                [[NSNotificationCenter defaultCenter ]postNotificationName:@"initQgx" object:aNotify];
                [[NSNotificationCenter defaultCenter ]postNotificationName:@"initQgxG" object:aNotify];
                
                break;
            case forNOTICE_POSSHARE_QUITRGROUP:
                // 共享退出
                [[NSNotificationCenter defaultCenter ]postNotificationName:@"initdata" object:aNotify];
                break;
            case forNotifyGONGXIANGZHONGZHI:
                // 共享退出
                [[NSNotificationCenter defaultCenter ]postNotificationName:@"gongxiangzhongzhi" object:aNotify];
                [[NSNotificationCenter defaultCenter ]postNotificationName:@"gongxiangzhongzhig" object:aNotify];
                [[NSNotificationCenter defaultCenter ]postNotificationName:@"gongxiangzhongzhic" object:aNotify];
                break;
            default:
//                [[NSNotificationCenter defaultCenter ]postNotificationName:@"getMessageList" object:aNotify];
                [[NSNotificationCenter defaultCenter ]postNotificationName:@"xhwgetMessageList" object:aNotify];  //xhw2018-2-11改:因为收到消息的时候也会发这个名字的通知，聊天界面也有添加这个通知的观察者，然后取里面的formid程序崩溃，所以改一个通知名字
                [self showMsgCount];
                break;
                
        }
    }
}


-(void)tcResultNoneError:(TCError *)itemE{
    NSLog(@"%@",itemE);
}

//此方法会在设备横竖屏变化的时候调用
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window
{
    
    //   NSLog(@"方向  =============   %ld", _allowRotate);
    if (_allowRotate == 1) {
        return UIInterfaceOrientationMaskAll;
    }else{
        return (UIInterfaceOrientationMaskPortrait);
    }
}

//-(void)openURL:(NSString *)urlString{
//    NSURL *url = [NSURL URLWithString:urlString];
//    [[UIApplication sharedApplication] openURL:url];
//}


// 返回是否支持设备自动旋转
- (BOOL)shouldAutorotate
{
    if (_allowRotate == 1) {
        return YES;
    }
    return NO;
}

- (void)initializeAudios {
    NSURL *url1=[[NSBundle mainBundle]URLForResource:@"audio_msg_rec" withExtension:@"caf"];

    AudioServicesCreateSystemSoundID((__bridge CFURLRef)url1, &_soundDidRecMsg);
    
    NSURL *url2=[[NSBundle mainBundle]URLForResource:@"audio_msg_send" withExtension:@"caf"];
    
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)url2, &_soundDidSendMsg);
    
    NSURL *url3=[[NSBundle mainBundle]URLForResource:@"audio_msg_rec" withExtension:@"caf"];
    
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)url3, &_soundDidRecNotify);
    //把需要销毁的音效文件的ID传递给它既可销毁
    //AudioServicesDisposeSystemSoundID(soundID);
    
    //3.播放音效文件
    //下面的两个函数都可以用来播放音效文件，第一个函数伴随有震动效果
//    AudioServicesPlayAlertSound(soundID);
    //AudioServicesPlaySystemSound(<#SystemSoundID inSystemSoundID#>)
}

- (void)shareTextToPlatformType:(UMSocialPlatformType)platformType {
    UMSocialLogError(@"这是error日志");
    return;
}


@end
